package com.fenquen.dfs.router.test.multicast;


import com.fenquen.dfs.router.config.DFSRouterConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ChannelFactory;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class MulticastServer extends Thread {
    private static final Logger LOGGER = LoggerFactory.getLogger(MulticastServer.class);

    @Autowired
    private DFSRouterConfig dfsRouterConfig;

    /**
     * 组播地址
     */
    private InetSocketAddress groupAddress;

    public MulticastServer(InetSocketAddress groupAddress) {
        this.groupAddress = groupAddress;
    }

    public void run() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            // NetworkInterface ni = NetworkInterface.getByName("en1");
            NetworkInterface ni = NetUtil.LOOPBACK_IF;
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            InetAddress localAddress = null;
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    localAddress = address;
                }
            }

            Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup)
                    .channelFactory(new ChannelFactory<NioDatagramChannel>() {

                        public NioDatagramChannel newChannel() {
                            NioDatagramChannel nioDatagramChannel = new NioDatagramChannel(InternetProtocolFamily.IPv4);
                            System.out.println(nioDatagramChannel);
                            return nioDatagramChannel;
                        }
                    })
                    .localAddress("0.0.0.0", groupAddress.getPort())
                    // .option(ChannelOption.IP_MULTICAST_IF, NetworkInterface.getByInetAddress(InetAddress.getByName("192.168.100.60")))
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        public void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(new MulticastServerHandler());
                            System.out.println("server");
                        }
                    });

            DatagramChannel channel = (DatagramChannel) bootstrap.bind().sync().channel();
            channel.localAddress();
            channel.joinGroup(groupAddress, NetworkInterface.getByInetAddress(InetAddress.getByName("192.168.43.125")));
            //  ch.closeFuture().await();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        InetSocketAddress groupAddress = new InetSocketAddress("224.101.102.106", 4000);
        new MulticastServer(groupAddress).start();
    }
}
